<?php

namespace app\admin\controller\statistics;

use app\admin\controller\entrepot\Receiving;
use app\admin\controller\other\Process;
use app\admin\library\Auth;
use app\admin\model\Colour;
use app\admin\model\develop\Acuisitionscheme;
use app\admin\model\entrepot\Deliver;
use app\admin\model\other\Processattribute;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 订单明细管理
 *
 * @icon fa fa-circle-o
 */
class Orderdetail extends Backend
{

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['is_overstep'];

    /**
     * Orderdetail模型对象
     * @var \app\admin\model\statistics\Orderdetail
     */
    protected $model = null;
//    protected $modelValidate = true;
    protected $modelSceneValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\statistics\Orderdetail;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $ids = $this->request->get('ids');
            if ($ids) {
                $where1['orderdetail.order_id'] = $ids;
            } else {
                $where1 = '';
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['order', 'colour'])
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'trademark_printing', 'abbreviation', 'quantity', 'cumulative_quantity', 'createtime', 'updatetime', 'status', 'process_detail']);
                $row->visible(['order']);
                $row->getRelation('order')->visible(['order_no']);
                $row->visible(['colour']);
                $row->getRelation('colour')->visible(['name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
//p($result);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $orderDetailModel = new \app\admin\model\statistics\Orderdetail();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                //判断当前订单下是否有相同商标印字和色号的明细
                $checkWhere['order_id'] = $params['order_id'];
                $checkWhere['trademark_printing'] = $params['trademark_printing'];
                $checkWhere['colour_id'] = $params['colour_id'];
                $issetDetail = Db::name('order_detail')->where($checkWhere)->count();
                if($issetDetail > 0){
                    $this->error('当前订单下已经存在相同数据');
                }

                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    //执行添加
                    $result = $this->model->allowField(true)->save($params);
                    if (!$result) {
                        Db::rollback();
                        $this->error('添加失败');
                    }
                    $order_detail_id = $this->model->getLastInsID();


//                  添加产品订单信息 -》 添加物料方案-》领料方案-》生成发料信息-》生成发料料信息 -》生成收料信息-》添加订单工序信息

                    //查询物料方案
                    $materialplan = new \app\admin\model\statistics\Materialplan;
                    $materialplan_where['trademark_printing'] = $params['trademark_printing'];
                    $materialplan_where['colour_id'] = $params['colour_id'];
                    $materialplanArr = collection($materialplan->where($materialplan_where)->order('id','desc')->select())->toArray();
                    if(count($materialplanArr) > 0){//存在物料方案
                        //获取主方案数据
                        $materialplanData = [];
                        foreach ($materialplanArr as $k => $v){
                            if ($v['attribute'] == 1){
                                $materialplanData = $v;
                                break;
                            }
                        }
                        if(!$materialplanData){
                            $materialplanData = $materialplanArr[count($materialplanArr)-1];
                        }

                        //领料方案
                        $acquisitionscheme = new Acuisitionscheme();
                        $acquisitionscheme_insert['order_id'] = $params['order_id'];
                        $acquisitionscheme_insert['order_detail_id'] = $order_detail_id;
                        $acquisitionscheme_insert['colour_id'] = $params['colour_id'];
                        $acquisitionscheme_insert['material_plan_id'] = $materialplanData['id'];

                        if($materialplanData['status'] == 1){
                            //如果领料方案状态为已处理，生成领料方案
                            if(!$acquisitionscheme->save($acquisitionscheme_insert)){
                                Db::rollback();
                                $this->error('添加失败1');
                            }

                            $order_detail_update['status'] = 1;
                        }else{
                            //如果状态等于0、2、3
                            if($materialplanData['status'] == 0){
                                $order_detail_update['status'] = 0;
                            }else{
                                //获取物料方案审核表是否存在已经审核通过记录
                                $materialPlanAuditModel =new \app\admin\model\statistics\Materialplanaudit();
                                $w['pid'] = $materialplanData['id'];
                                $w['status'] = 1;
                                $isHadAuditData = $materialPlanAuditModel->where($w)->count();

                                if($isHadAuditData == 0){
                                    $order_detail_update['status'] = 0;
                                }else{
                                    //如果存在审核通过的记录，生成领料方案
                                    if(!$acquisitionscheme->save($acquisitionscheme_insert)){
                                        Db::rollback();
                                        $this->error('添加失败2');
                                    }
                                    $order_detail_update['status'] = 1;
                                }
                            }
                        }

                        $where['id'] = $order_detail_id;
                        if($order_detail_update['status'] == 1 && !$orderDetailModel::where($where)->update($order_detail_update)){
                            Db::rollback();
                            $this->error('添加失败3');
                        }
                    }else{//不存在，添加物料方案
                        $materialplan_insert['trademark_printing'] = $params['trademark_printing'];
                        $materialplan_insert['abbreviation'] = $params['abbreviation'];
                        $materialplan_insert['colour_id'] = $params['colour_id'];
                        $materialplan_re = $materialplan->insert($materialplan_insert);
                    }

                    //判断是否存在商品工序
                    $processWhere['trademark_printing'] = $params['trademark_printing'];
                    $processArr = Db::name('process')->where($processWhere)->select();
                    if ($processArr && is_array($processArr)) {
                        foreach ($processArr as $key => $val) {
                            $colourArr = explode(',', $val['colour_ids']);
                            if (in_array($params['colour_id'], $colourArr)) {
                                $processList = explode(',', $val['process_attribute_ids']);
                                $process_detail = [];
                                foreach ($processList as $k2 => $v2) {
                                    $new_data['process_attribute'] = $v2;
                                    $new_data['quantity'] = 0; //工序收取量
                                    $new_data['schedule'] = 0; //工序进度=工序累计收取量/订单总数*100
                                    $new_data['weights'] = 0; //工序权重 = 工序收取量/色号收取总数*工序进度/100
                                    $process_detail[] = $new_data;
                                }
                                $upOrderDetail['process_detail'] = json_encode($process_detail, JSON_UNESCAPED_UNICODE);
                                $re = Db::name('order_detail')->where('id', 'eq', $order_detail_id)->update($upOrderDetail);
                                break;
                            }
                        }
                        //更细订单进度
                        up_order_schedule($order_detail_id);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {

                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    if ($result) {
                        //                    判断是否超单
                        $quantity = $params["quantity"];
                        $re = collection($this->model->where('id', 'eq', $ids)->limit(1)->select())->toArray();
                        $orderDetail = $re[0];

                        if (boolval(trim($orderDetail['process_detail']))) {

                            $processList = \GuzzleHttp\json_decode($orderDetail['process_detail'], true);

                            if ($processList && is_array($processList)) {
                                //更新订单状态
                                $orderModel = new \app\admin\model\statistics\Order();
                                $max = 0;
                                foreach ($processList as $k => $v) {
                                    $max = $v['quantity'] > $max ? $v['quantity'] : $max;
                                }

                                if ($max > $quantity) {
                                    $orderModel->where('id', 'eq', $orderDetail['order_id'])->setField('status', 0);
                                    //更新订单明细状态

                                    $this->model->where('id', 'eq', $ids)->setField('status', 3);
                                } else {
                                    $orderModel->where('id', 'eq', $orderDetail['order_id'])->setField('status', 1);
                                    //更新订单明细状态
                                    $acquisition_scheme = Db::name('acquisition_scheme')->where('order_detail_id', 'eq', $orderDetail['id'])->count();

                                    $orderDetailStatus = $acquisition_scheme > 0 ? 1 : 0;
                                    $this->model->where('id', 'eq', $ids)->setField('status', $orderDetailStatus);
                                }
                            }


                        }
                        //更细订单进度
                        up_order_schedule($row['order_id']);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {

                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if (boolval(trim($row['process_detail']))) {
            $process_detail = \GuzzleHttp\json_decode($row['process_detail'], true);

            foreach ($process_detail as $k => $v) {
                $process_detail[$k]['process_name'] = Db::name('process_attribute')->where('id="' . $v['process_attribute'] . '"')->value('name');
            }
            $row['process_detail'] = json_encode($process_detail, JSON_UNESCAPED_UNICODE);
        }


        $type = $this->request->get("type");
        if ($type == 'ordershowdetail') {
            $row['order_no'] = Db::name('order')->where('id="' . $row['order_id'] . '"')->value('order_no');
            $row['colour_name'] = Db::name('colour')->where('id="' . $row['colour_id'] . '"')->value('name');
            $this->view->assign("row", $row);
            return $this->view->fetch('statistics/order/ordershowdetail');
        } else {
            $this->view->assign("row", $row);
            return $this->view->fetch();
        }
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                $receivingModel = new \app\admin\model\entrepot\Receiving();
                $acuisitionschemeModel = new Acuisitionscheme();
                $acuisitionschemedetailModel = new \app\admin\model\statistics\Acquisitionschemedetail();
                $is_received = 0;
                foreach ($list as $k => $v) {
                    $w['order_detail_id'] = $v['id'];
                    $re = $receivingModel->where($w)->count();
                    if ($re > 0) $is_received += $re;
                    break;
                }

                if ($is_received <= 0) {
                    foreach ($list as $k => $v) {
                        $count += $v->delete();
                        //删除领料方案数据
                        $acuisitionschemeModel->where('order_detail_id', 'eq', $v['id'])->delete();
                        //删除领料明细
                        $acuisitionschemedetailModel->alias('ad')
                            ->join('acuisitionscheme a','a.id = ad.acquisition_scheme_id')
                            ->where('a.order_detail_id','eq',$v['id'])
                            ->fetchSql()
                            ->delete();

                        //删除发料信息
                        $deliverModel = new \app\admin\model\Deliver();
                        $deliverModel->where('order_detail_id','eq',$v['id'])->delete();

                        if ($v['process_detail'] != NULL && !in_array()) {
                            //重新计算订单进度
                            up_order_schedule($v['order_id']);
                        }
                    }
                } else {
                    Db::rollback();
                    $this->error(__('已有收货记录无法删除'));
                }
//                p(1);
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function is_overstep($ids = null)
    {
        $result = array(
            'code' => 1,
            'msg' => '正常'
        );
        $ids = $ids ? $ids : $this->request->post("id");
        $quantity = $this->request->post("quantity");
        $quantity = $quantity ? $quantity : 0;

        $re = collection($this->model->where('id', 'eq', $ids)->limit(1)->select())->toArray();

        if ($re && isset($re[0])) $orderDetail = $re[0];
        if (isset($orderDetail['process_detail']) && $orderDetail['process_detail']) {
            $processList = json_decode($orderDetail['process_detail'], true);
            if ($processList && is_array($processList)) {
                $max = 0;
                foreach ($processList as $k => $v) {
                    $max = $v['quantity'] > $max ? $v['quantity'] : $max;
                }
//                p($max.'||'.$quantity);
                if ($max > $quantity) {
                    $result = array(
                        'code' => 0,
                        'msg' => '超单'
                    );
                }
            }

        }
        return json($result);
    }

    /**
     * @return string
     */
    public function process_detail($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $process = new Processattribute();
        $process_detail_arr = json_decode($row['process_detail'], true);
        if ($process_detail_arr) {
//            {"process_attribute":"3","quantity":1000000,"schedule":100,"weights":0.33}]
            foreach ($process_detail_arr as $k => $v) {
                $where['id'] = $v['process_attribute'];
                $process_detail_arr[$k]['process_attribute'] = $process->where($where)->value('name');
            }
        }

        $this->view->assign("process_detail", json_encode($process_detail_arr));
        return $this->view->fetch();
    }

    /**
     * @return void
     * by lhq
     */
    public function import()
    {
        ini_set('max_execution_time', '0');
        $orderIdArr = [];
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);

        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表

            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号

            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            $orderList = Db::name('order')->field('id,order_no')->select();
            $colourList = Db::name('colour')->field('id,name')->select();

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
//                p($temp);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $v !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }

                if ($row) {
                    $order_id=0;
                    foreach ($orderList as $v){
                        if($v['order_no'] == $row['order_id']){
                            $order_id = $v['id'];
                            break;
                        }
                    }

//                    $order_id = Db::name('order')->where('order_no', 'eq', $row['order_id'])->value('id');
                    if (!$order_id) {
                        $this->error(__("无法导入数据，订单号[" . $row['order_id'] . "]未录入"));
                    }

                    $colour_id = 0;
                    foreach ($colourList as $v){
                        if($v['name'] == $row['colour_id']){
                            $colour_id = $v['id'];
                            break;
                        }
                    }
//                    $colour_id = Db::name('colour')->where('name', 'eq', $row['colour_id'])->value('id');
                    if (!$colour_id) $this->error(__("无法导入数据，色号[" . $row['colour_id'] . "]未录入"));

                    if ($order_id && $colour_id) {
                        $where['order_id'] = $order_id;
                        $where['colour_id'] = $colour_id;
                        $where['trademark_printing'] = $row['trademark_printing'];
                        $isSet = $this->model->where($where)->find();
                        if (!$isSet) {
                            $row['order_id'] = $order_id;
                            $row['colour_id'] = $colour_id;
                            $insert[] = $row;
                        } else {
                            $this->error(__("无法导入数据，[" . $row['order_id'] . "-" . $row['trademark_printing'] . "-" . $row['colour_id'] . "]已经存在"));
                        }
                    }
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }


        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        Db::startTrans();
        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $re = $this->model->saveAll($insert);

            if ($re) {
                $materialPlanAuditModel = new \app\admin\model\statistics\Materialplanaudit();
                $materialplan = new \app\admin\model\statistics\Materialplan;
                $acquisitionscheme = new Acuisitionscheme();
                $processModel = new \app\admin\model\Process();
                foreach ($re as $v) {
//                  添加产品订单信息 -》 添加物料方案-》领料方案-》生成发料信息-》生成发料料信息 -》生成收料信息-》添加订单工序信息

                    //查询物料方案
                    $materialplan_where['trademark_printing'] = $v->trademark_printing;
                    $materialplan_where['colour_id'] = $v->colour_id;
                    $materialplanArr = collection($materialplan->where($materialplan_where)->order('id','desc')->select())->toArray();
                    if(count($materialplanArr) > 0){//存在物料方案
                        //获取主方案数据
                        $materialplanData = [];
                        foreach ($materialplanArr as  $v2){
                            if ($v2['attribute'] == 1){
                                $materialplanData = $v2;
                                break;
                            }
                        }
                        if(!$materialplanData){
                            $materialplanData = $materialplanArr[count($materialplanArr)-1];
                        }

                        //领料方案
                        $acquisitionscheme_insert['order_id'] = $v->order_id;
                        $acquisitionscheme_insert['order_detail_id'] = $v->id;
                        $acquisitionscheme_insert['colour_id'] = $v->colour_id;
                        $acquisitionscheme_insert['material_plan_id'] = $materialplanData['id'];

                        if($materialplanData['status'] == 1){
                            //如果领料方案状态为已处理，生成领料方案
                            if(!$acquisitionscheme->save($acquisitionscheme_insert)){
                                Db::rollback();
                                $this->error('添加失败1');
                            }

                            $order_detail_update['status'] = 1;
                        }else{
                            //如果状态等于0、2、3
                            if($materialplanData['status'] == 0){
                                $order_detail_update['status'] = 0;
                            }else{
                                //获取物料方案审核表是否存在已经审核通过记录
                                $w['pid'] = $materialplanData['id'];
                                $w['status'] = 1;
                                $isHadAuditData = $materialPlanAuditModel->where($w)->count();

                                if($isHadAuditData == 0){
                                    $order_detail_update['status'] = 0;
                                }else{
                                    //如果存在审核通过的记录，生成领料方案
                                    if(!$acquisitionscheme->save($acquisitionscheme_insert)){
                                        Db::rollback();
                                        $this->error('添加失败2');
                                    }
                                    $order_detail_update['status'] = 1;
                                }
                            }
                        }

                        $where['id'] = $v->id;
                        $this->model::where($where)->update($order_detail_update);
//                        if($order_detail_update['status'] == 1 && !$this->model::where($where)->update($order_detail_update)){
//                            Db::rollback();
//                            $this->error('添加失败3');
//                        }
                    }else{//不存在，添加物料方案
                        $materialplan_insert['trademark_printing'] = $v->trademark_printing;
                        $materialplan_insert['abbreviation'] = $v->abbreviation;
                        $materialplan_insert['colour_id'] = $v->colour_id;
                        $materialplan->insert($materialplan_insert);
                    }

                    //判断是否存在商品工序
                    $processWhere['trademark_printing'] = $v->trademark_printing;
                    $processArr = collection($processModel->where($processWhere)->select())->toArray();
                    if ($processArr && is_array($processArr)) {
                        foreach ($processArr as $key => $val) {
                            $colourArr = explode(',', $val['colour_ids']);
                            if (in_array($v->colour_id, $colourArr)) {
                                $processList = explode(',', $val['process_attribute_ids']);
                                $process_detail = [];
                                foreach ($processList as  $v3) {
                                    $new_data['process_attribute'] = $v3;
                                    $new_data['quantity'] = 0; //工序收取量
                                    $new_data['schedule'] = 0; //工序进度=工序累计收取量/订单总数*100
                                    $new_data['weights'] = 0; //工序权重 = 工序收取量/色号收取总数*工序进度/100
                                    $process_detail[] = $new_data;
                                }
                                $upOrderDetail['process_detail'] = json_encode($process_detail, JSON_UNESCAPED_UNICODE);
                                $this->model->where('id', 'eq', $v->id)->update($upOrderDetail);
                                break;
                            }
                        }

                    }
                    //更细订单进度
//                    up_order_schedule($v->order_id);
                    if(in_array($v->order_id,$orderIdArr)) $orderIdArr[] = $v->order_id;
//
//
//
////                    判断是否存在物料方案
//                    $materialplan_where['trademark_printing'] = $v->trademark_printing;
//                    $materialplan_where['colour_id'] = $v->colour_id;
//                    $materialplan_where['status'] = ['neq', 0];
//                    $materialplan_data = $materialplan->where($materialplan_where)->limit(1)->order('id desc')->find();
//
//                    if ($materialplan_data) {//存在
//                        //组装领料方案数据
//                        $acquisitionscheme_insert['order_id'] = $v->order_id;
//                        $acquisitionscheme_insert['order_detail_id'] = $v->id;
//                        $acquisitionscheme_insert['colour_id'] = $v->colour_id;
//
//                        //把发料方案关联的物料方案id改为关联审核表中的id
////                        $materialplanaudit_where['status'] = ['eq', 0]; //待处理
////                        $materialplanaudit_where['pid'] = ['eq', $materialplan_data['id']];
////                        $materialplanaudit_data = $materialplanaudit->where($materialplanaudit_where)->limit(1)->order('id', 'desc')->find();
//                        //添加领料方案
//                        $acquisitionscheme_insert['material_plan_id'] = $materialplan_data['id'];
//
//                        $acquisitionscheme->save($acquisitionscheme_insert);
//                        //更新订单详情数据
//                        $order_detail_update['id'] = $v->id;
//                        $order_detail_update['status'] = $materialplan_data['status'] == 0 ? 0 : 1;
//                        $this->model->isUpdate(true)->save($order_detail_update);
////                        }
//                    } else {
//                        //不存在，添加物料方案
//                        $materialplan_insert['trademark_printing'] = $v->trademark_printing;
//                        $materialplan_insert['abbreviation'] = $v->abbreviation;
//                        $materialplan_insert['colour_id'] = $v->colour_id;
//                        $materialplan->save($materialplan_insert);
//                    }
//
//                    //判断是否存在商品工序
//                    $processWhere['trademark_printing'] = $v->trademark_printing;
//                    $processArr = collection($processModel->where($processWhere)->select())->toArray();
//
//                    if ($processArr && is_array($processArr)) {
//                        foreach ($processArr as $key => $val) {
//                            $colourArr = explode(',', $val['colour_ids']);
//                            if (in_array($v->colour_id, $colourArr)) {
//                                $processList = explode(',', $val['process_attribute_ids']);
//                                $process_detail = [];
//                                foreach ($processList as $k2 => $v2) {
//                                    $new_data['process_attribute'] = $v2;
//                                    $new_data['quantity'] = 0; //工序收取量
//                                    $new_data['schedule'] = 0; //工序进度=工序累计收取量/订单总数*100
//                                    $new_data['weights'] = 0; //工序权重 = 工序收取量/色号收取总数*工序进度/100
//                                    $process_detail[] = $new_data;
//                                }
//                                $upOrderDetail['id'] = $v->id;
//                                $upOrderDetail['process_detail'] = json_encode($process_detail, JSON_UNESCAPED_UNICODE);
//                                $this->model->isUpdate(true)->save($upOrderDetail);
//                                break;
//                            }
//                        }
//
//                    }
//                    //更细订单进度
//                    if(!in_array($v->order_id,$orderIdArr)) $orderIdArr[] = $v->order_id;
                }
            }

        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            p(db()->getLastSql());
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
//            p($e->getMessage());
            $this->error($e->getMessage());
        }
        foreach ($orderIdArr as $v){
            up_order_schedule($v);
        }
        Db::commit();
        $this->success();
    }

}
